package com.gitee.gateway.core.utils;

import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.common.template.TemplateEngine;
import io.vertx.ext.web.templ.httl.HTTLTemplateEngine;

import java.util.Locale;

/**
 * 支持多语言的模板加载器
 */
public class MultipleLanguageTemplateEngine {

    private final static String BASE = "/html/";

    /**
     * 根据指定的语言加载模板内容进行渲染
     *
     * @param vertx        Vertx实例
     * @param templateName 模板名称
     * @param args         模板参数
     * @param locale       语言
     * @return 渲染后的内容
     */
    public static Future<Buffer> render(Vertx vertx, String templateName, JsonObject args, Locale locale) {
        if (locale == null)
            locale = Locale.getDefault();
        String tplName = BASE + templateName + "_" + locale.getLanguage() + "_" + locale.getCountry() + ".html";
        if (MultipleLanguageTemplateEngine.class.getResource(tplName) == null) {
            tplName = BASE + templateName + "_" + locale.getLanguage() + ".html";
            if (MultipleLanguageTemplateEngine.class.getResource(tplName) == null) {
                tplName = BASE + templateName + ".html";
                if (MultipleLanguageTemplateEngine.class.getResource(tplName) == null) {
                    return Future.failedFuture("Template not found: " + tplName);
                }
            }
        }
        TemplateEngine tmpl = HTTLTemplateEngine.create(vertx, "html");
        return tmpl.render(args, tplName.substring(0, tplName.lastIndexOf('.')));
    }

    public static void main(String[] args) {
        System.out.println(MultipleLanguageTemplateEngine.class.getResource("/html/verify_code_email.html"));
        String name = "verify_code_email";
        render(Vertx.vertx(), name, new JsonObject(), Locale.ENGLISH)
                .onSuccess(System.out::println)
                .onFailure(Throwable::printStackTrace);
    }
}
